<style lang="stylus" scoped>

</style>

<template>
  <div>
    <q-table
      class="bg-white shadow-1"
      :data="data"
      dense
      :columns="columns"
      row-key="id"
      separator="cell"
      selection="multiple"
      :selected.sync="selected"
      :visible-columns="visibleColumns"
      :filter="searchForm"
      :pagination.sync="pagination"
      :rows-per-page-options="[3, 5, 10, 20]"
      no-data-label="暂无数据"
      table-class="h-custom"
      @request="listGet"
    >
      <template v-slot:top-left="props">
        <q-btn size="sm" color="light-blue" :label="$t('新增')" @click="add"/>
        <!-- <q-btn color="negative" flat :label="$t('批量删除')" class="q-ml-sm"/> -->
      </template>
      <template v-slot:top-right="props">
        <q-select
          v-model="visibleColumns"
          multiple
          borderless
          options-dense
          :display-value="$t('显示列')"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          class="q-mx-lg"
        >
          <template v-slot:option="scope">
            <q-item
              v-bind="scope.itemProps"
              v-on="scope.itemEvents"
              v-if="!scope.opt.required"
            >
              <q-item-section avatar>
                <q-toggle color="blue" v-model="visibleColumns" :val="scope.opt.name" />
              </q-item-section>
              <q-item-section style="min-width:60px">
                {{ scope.opt.label }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-toggle
          v-model="searchToggle"
          left-label
          label="搜索"
          color="blue"
          checked-icon="check"
          unchecked-icon="clear"
          keep-color
        />
        <q-btn
          flat round dense
          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
          @click="props.toggleFullscreen"
          class="q-ml-md"
        />
      </template>
      <template v-if="searchToggle" v-slot:top-row="props">
        <q-tr :props="props">
          <q-td>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
            <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchForm })"/>
            <q-input dense outlined v-model="searchForm[col.name]" v-else/>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th>
            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
          </q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td width="52">
            <q-checkbox dense v-model="props.selected" />
          </q-td>
          <q-td key="action" :props="props">
            <q-btn-dropdown
              color="blue"
              size="sm"
              dense
              menu-anchor="bottom left"
              menu-self="top left"
              content-class="text-grey"
              icon="settings">
              <q-list dense>
                <q-item clickable v-close-popup @click="edit(props.row)">
                  <q-item-section>
                    <q-item-label>修改</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="delRow(props.row)">
                  <q-item-section>
                    <q-item-label>删除</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="props.expand = !props.expand">
                  <q-item-section>
                    <q-item-label>{{ props.expand? '收起': '更多字段' }}</q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </q-td>
          <q-td key="code" :props="props">{{ props.row.code  }}</q-td>
          <q-td key="name" :props="props">{{ props.row.name }}</q-td>
          <q-td key="typeName" :props="props">{{ props.row.typeName }}</q-td>
          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="props">
        <q-pagination
          v-model="pagination.page"
          color="blue"
          :max-pages="5"
          :max="pages"
          :boundaryLinks="true"
          :directionLinks="true"
        />
        共 {{ total }} 条
      </template>
    </q-table>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '新增' : '修改'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <q-tabs
            v-model="addOrEditTab"
            dense
            class="text-grey-9"
            active-color="primary"
            indicator-color="primary"
            align="left"
            :breakpoint="0"
            narrow-indicator
          >
            <q-tab name="tab1" label="业务组织属性" />
            <!-- <q-tab name="tab2" label="品类" :disable="!addOrEditForm.id"/> -->
          </q-tabs>
          <q-separator />
          <q-tab-panels v-model="addOrEditTab" animated>
            <q-tab-panel name="tab1" class="row q-col-gutter-sm">
              <div class="col-12">
                <div :class="$v.addOrEditForm.code.$error?'text-negative': ''">业务组织编码</div>
                <q-input
                  v-model="addOrEditForm.code"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.code.$error"
                  @blur="$v.addOrEditForm.code.$touch"
                  dense hint :disable="addOrEdit !== 1"/>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForm.name.$error?'text-negative': ''">业务组织名称</div>
                <q-input
                  v-model="addOrEditForm.name"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.name.$error"
                  @blur="$v.addOrEditForm.name.$touch"
                  dense hint/>
              </div>
              <div class="col-12">
                <div>业务组织名称（英）</div>
                <q-input
                  v-model="addOrEditForm.nameEn"
                  dense hint/>
              </div>
              <div class="col-12">
                <div :class="$v.addOrEditForm.type.$error?'text-negative': ''">业务组织类型</div>
                <q-select
                  dense hint
                  v-model="addOrEditForm.type"
                  error-message="该字段为必填项"
                  :error="$v.addOrEditForm.type.$error"
                  @blur="$v.addOrEditForm.type.$touch"
                  :options="options"
                  option-value="id"
                  option-label="name"
                  emit-value
                  map-options
                />
              </div>
            </q-tab-panel>

            <q-tab-panel name="tab2">
              <q-tree
                color="light-blue"
                :nodes="nodes"
                node-key="id"
                label-key="name"
                tick-strategy="leaf"
                :ticked.sync="ticked"
                default-expand-all
              >
                <template v-slot:header-input="prop">

                </template>
              </q-tree>
            </q-tab-panel>
          </q-tab-panels>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <!-- <q-btn v-if="!addOrEditForm.id" flat label="保存并维护品类" color="primary" :disable="loadingSave" :loading="loadingSingleSave" @click="saveSingleHandler">
            <q-tooltip anchor="top middle" self="bottom middle" :offset="[5, 5]" content-class="bg-black text-white">
              <div style="width:150px;font-size:11px">
                该操作会保存您在“业务组织属性”一栏填写的全部信息，并且不会关闭当前会话框，以便于您继续为该业务组织维护品类。
              </div>
            </q-tooltip>
          </q-btn> -->
          <q-space/>
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :disable="loadingSingleSave" :loading="loadingSave" @click="saveHandler" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { required } from 'vuelidate/lib/validators'
import { transformToTreeFormat } from 'src/utils/fns'
export default {
  name: 'BusinessOrg',
  data () {
    return {
      searchToggle: false,
      searchForm: {
        name: '',
        code: '',
        createTime: ''
      },
      selected: [],
      visibleColumns: [
        'action',
        'name',
        'code',
        'createTime'
      ],
      // 当加入 required: true 属性时  visibleColumns 对当前字段无效
      columns: [
        { name: 'action', align: 'center', label: '操作' },
        { name: 'code', required: true, label: '业务组织编码', align: 'left', field: 'code', sortable: true },
        { name: 'name', required: true, label: '业务组织名称', align: 'left', field: 'name', sortable: true },
        { name: 'typeName', required: true, label: '业务组织类型', align: 'left', field: 'typeName', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      data: [],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      // dialog
      addOrEdit: 1, // 1 新增  2 修改
      loadingSave: false,
      loadingSingleSave: false,
      addOrEditDialog: false,
      maximizedToggle: false,
      addOrEditTab: 'tab1',
      addOrEditForm: {
        name: '',
        nameEn: '',
        type: '',
        code: Number
      },
      // tree
      nodes: [],
      ticked: [],
      // options
      options: []
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      code: { required },
      type: { required }
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/mdm/businessOrg/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    async add () {
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        code: null,
        name: '',
        nameEn: '',
        type: ''
      }
      this.ticked = []
      this.$v.addOrEditForm.$reset()
      await this.optionsGet()
      this.addOrEditDialog = true
    },
    async edit (row) {
      await Promise.all([
        this.$api({
          method: 'get',
          url: `/mdm/businessOrg/findById/${row.id}`,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            this.addOrEditForm = { ...data }
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        }),
        this.optionsGet()
      ])
      this.addOrEditDialog = true
      this.addOrEdit = 2
      this.addOrEditTab = 'tab1'
      this.$v.addOrEditForm.$reset()
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await Promise.all([
          this.$api({
            method: 'put',
            url: this.addOrEdit === 1 ? '/mdm/businessOrg/add' : '/mdm/businessOrg/update',
            params: this.addOrEditForm,
            emulateJSON: true,
            useNotify: true,
            successCallback: ({ data }) => {
              this.addOrEditDialog = false
            },
            errorCallback (err) {
              console.log('未处理的业务级error：', err)
            }
          })
          // this.selectCatUpdate(this.addOrEditForm.id)
        ])
        this.loadingSave = false
        this.init()
      }
    },
    async saveSingleHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSingleSave = true
        await this.$api({
          method: 'put',
          url: '/mdm/businessOrg/add',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.addOrEditForm = { ...data }
            this.addOrEdit = 2
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSingleSave = false
        this.init()
      }
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除业务组织：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/mdm/businessOrg/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    // 权限数据 获取
    async nodesCatGet () {
      await this.$api({
        method: 'post',
        url: '/mdm/category/selectAllByTenantId',
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.nodes = transformToTreeFormat(data, 'id', 'parentId', 'children')
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async selectCatGet (id) {
      await this.$api({
        method: 'post',
        url: '/mdm/groupcategory/query',
        params: {
          groupId: id
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.ticked = data
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    selectCatUpdate (id) {
      this.$api({
        method: 'put',
        url: '/mdm/groupcategory/updateGroupCategoryList',
        params: {
          groupId: id,
          categoryIds: this.ticked.join(',')
        },
        emulateJSON: true,
        useNotify: true,
        successCallback: ({ data }) => {

        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async optionsGet () {
      await this.$api({
        method: 'post',
        url: '/mdm/businessOrgType/queryNoPage',
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.options = data
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    }
  }
}
</script>
